package nl.saxion.security.gui.elements;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import nl.saxion.security.config.Config;
import nl.saxion.security.encryption.TransformerAES;
import nl.saxion.security.init.MainModule;

import nl.saxion.security.serverconfig.ServerConfig;
import nl.saxion.security.synchronize.ServerSynchronize;

import com.adamtaft.eb.EventBusService;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class PassPanel extends AbstractPassPanel {

	private static final long serialVersionUID = 1784803763927884351L;

	private JLabel helpLabel;

	private static JTextField pass;

	private JButton passChange;

	private Config config;

	private ServerConfig sConfig;

	@Inject
	public PassPanel(@Named("DefaultConfig") Config c) {
		super();
		config = c;
		configure();
		sConfig = ServerConfig.getSingletonObject(config);

	}

	protected void configure() {
		setLayout(new BorderLayout());
		configureHelpLabel();
		configurePassSelector();
	}

	private void configureHelpLabel() {
		helpLabel = new JLabel("Typ het wachtwoord in dat u wilt gebruiken");
		add(helpLabel, BorderLayout.NORTH);
	}

	private void configurePassSelector() {
		JPanel panel = new JPanel();
		panel.setLayout(new GridBagLayout());

		pass = new JTextField();
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.weightx = 4.0;
		c.weighty = 1.0;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.anchor = GridBagConstraints.LINE_START;
		panel.add(pass, c);

		passChange = new JButton("Verander");
		passChange.addActionListener(new PassChangeAction());

		GridBagConstraints c2 = new GridBagConstraints();
		c2.gridx = 5;
		c2.gridy = 0;
		c2.weightx = 1.0;
		c2.weighty = 1.0;
		c2.fill = GridBagConstraints.HORIZONTAL;
		c2.anchor = GridBagConstraints.LINE_START;
		panel.add(passChange, c2);

		add(panel, BorderLayout.CENTER);
	}

	private class PassChangeAction implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (!pass.getText().equals("")) {
				String password = pass.getText();
				TransformerAES transformer = new TransformerAES();
				byte[] passwordByte = null;
				try {
					passwordByte = transformer.generateKey(password);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				password = transformer.asHex(passwordByte);

				config.setAsString(Config.KEY_SYNC_ENCR_PASS, password);

				sConfig.changePassword();
				
				pass.setText("");
			}
		}
	}

	public static void setPassText(String Text) {
		pass.setText(Text);
	}

	public String getPass() {
		return pass.getText();
	}

}
